<template>
  <div class="app-container">
    <div class="search-container">
      <el-form inline label-width="68px" ref="queryFromRef" :model="queryParams">
        <el-form-item label="名称">
          <el-input v-model="queryParams.name" placeholder="" />
        </el-form-item>
        <el-form-item label="编码">
          <el-input v-model="queryParams.code" placeholder="" />
        </el-form-item>

        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery"> <i-ep-refresh />重置 </el-button>
          <el-button v-hasPerm="['sys:dict:add']" type="success" @click.stop="handleOpenDialog()">
            <i-ep-plus />
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table v-loading="loading" stripe :data="list" style="width: 100%">
        <el-table-column label="ID" width="50" prop="id" />
        <el-table-column label="名称" width="300" prop="name" />
        <el-table-column label="编码" width="300" prop="code" />
        <el-table-column label="状态" width="100" prop="enabled">
          <template #default="scope">
            <el-tag v-if="scope.row.enabled" type="success">使用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="250">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:dict:update']"
              type="primary"
              link
              size="small"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              <i-ep-edit />
              修改
            </el-button>

            <el-button
              v-hasPerm="['sys:dict:updateItem']"
              type="warning"
              link
              size="small"
              @click.stop="handleUpdateItem(scope.row.id)"
            >
              <i-ep-edit />
              字典配置
            </el-button>

            <el-button
              v-hasPerm="['sys:dict:delete']"
              type="danger"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-drawer v-model="dialog.visible" :title="dialog.title" @close="handleCloseDialog" size="50%">
      <el-form ref="addFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-alert
          v-if="formData.id !== ''"
          title="修改配置下，不支持修改字典编码."
          type="warning"
          :closable="false"
        /><br />

        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="" />
        </el-form-item>

        <el-form-item label="编码" prop="code">
          <el-input v-model="formData.code" placeholder="" :readonly="formData.id != ''" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="formData.remark" placeholder="" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="formData.enabled">
            <el-radio :value="true">有效</el-radio>
            <el-radio :value="false">无效</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <el-drawer v-model="dialog2.visible" title="字典配置" @close="handleCloseDialogItem" size="90%">
      <el-card shadow="never" class="table-container">
        <template #header>
          <el-button type="success" v-hasPerm="['sys:config:query']" @click="handleQueryItem()">
            <i-ep-search />
            查询
          </el-button>
          <el-button type="primary" v-hasPerm="['sys:config:add']" @click="handleOpenNewItem()">
            <i-ep-plus />
            新增
          </el-button>
        </template>
        <el-table v-loading="loading2" stripe :data="list2" style="width: 100%">
          <el-table-column label="ID" width="50" prop="id" />
          <el-table-column label="字典label" width="200" prop="label" />
          <el-table-column label="字典value" width="200" prop="value" />
          <el-table-column label="状态" width="100" prop="enabled">
            <template #default="scope">
              <el-tag v-if="scope.row.enabled" type="success">使用</el-tag>
              <el-tag v-else type="info">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="200" prop="remark" />
          <el-table-column fixed="right" label="操作" width="250">
            <template #default="scope">
              <el-button
                v-hasPerm="['sys:dict:update']"
                type="primary"
                link
                size="small"
                @click.stop="handleOpenNewItem(scope.row.id)"
              >
                <i-ep-edit />
                修改
              </el-button>

              <el-button
                v-hasPerm="['sys:dict:delete']"
                type="danger"
                link
                size="small"
                @click.stop="handleDeleteItem(scope.row.id)"
              >
                <i-ep-delete />
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-if="total2 > 0"
          v-model:total="total2"
          v-model:page="queryParams2.pageNum"
          v-model:limit="queryParams2.pageSize"
          @pagination="handleQuery2"
        />
      </el-card>
    </el-drawer>

    <el-dialog
      v-model="dialog3.visible"
      :title="dialog3.title"
      width="500px"
      @close="handleCloseDialog3"
    >
      <el-form
        ref="dataFormItemRef"
        :rules="rulesItem"
        :model="formItemData"
        label-suffix=":"
        label-width="100px"
      >
        <el-form-item label="标签" prop="label">
          <el-input v-model="formItemData.label" placeholder="" :maxlength="50" />
        </el-form-item>
        <el-form-item label="值" prop="value">
          <el-input v-model="formItemData.value" placeholder="" :maxlength="50" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number
            v-model="formItemData.orderNum"
            style="width: 100px"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formItemData.enabled">
            <el-radio :value="true">有效</el-radio>
            <el-radio :value="false">无效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formItemData.remark" placeholder="" :maxlength="50" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmitItem">确定</el-button>
          <el-button @click="handleCloseDialogItemNew">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
defineOptions({
  name: 'PlatformDict',
  inheritAttrs: false
})

import { ElForm, ElTable } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
const BASE_URL = '/api/yyplatform/admin/sys/dict/'

const list = ref([])
const total = ref(0)
const loading = ref(false)

const addFormRef = ref(ElForm)
const formData = ref({
  id: '',
  name: '',
  code: '',
  orderNum: 0,
  remark: '',
  enabled: true
})
const queryFromRef = ref()
const dialog = ref({
  title: '',
  visible: false
})

const queryParams = ref({
  name: '',
  code: '',
  pageNum: 1,
  pageSize: 20
})

function handleCloseDialog() {
  dialog.value.visible = false
  dialog.value.title = '添加字典'
  formData.value = {
    id: '',
    name: '',
    code: '',
    remark: '',
    enabled: true
  }
}
async function handleOpenDialog(id) {
  if (id) {
    let res = await request({
      url: `${BASE_URL}/get?id=${id}`,
      method: 'get'
    })
    formData.value = res
    dialog.value.visible = true
    dialog.value.title = '修改字典'
  } else {
    formData.value = {
      id: '',
      name: '',
      code: '',
      remark: '',
      enabled: true
    }
    dialog.value.visible = true
    dialog.value.title = '添加字典'
  }
}
const rules = ref({
  code: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})
async function submitForm() {
  addFormRef.value.validate(async (isValid) => {
    if (isValid) {
      const id = formData.value.id
      if (id) {
        let updateRes = await request({
          url: `${BASE_URL}/update`,
          method: 'post',
          data: formData.value
        })
        ElMessage.success('修改成功')
        handleCloseDialog()
        await handleQuery()
      } else {
        let addRes = await request({
          url: `${BASE_URL}/save`,
          method: 'post',
          data: formData.value
        })
        ElMessage.success('添加成功')
        handleCloseDialog()
        await handleQuery()
      }
    }
  })
}
function handleDelete(id) {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      url: `${BASE_URL}/delete`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: {
        id: id
      }
    }).then(async () => {
      await handleQuery()
    })
  })
}

async function handleResetQuery() {
  queryParams.value = {
    name: '',
    code: '',
    pageNum: 1,
    pageSize: 20
  }
  await handleQuery()
}

async function handleQuery() {
  console.log(queryParams.value, 'queryParams')

  loading.value = true

  let queryRes = await request({
    url: `${BASE_URL}/query`,
    method: 'get',
    params: {
      ...queryParams.value
    }
  })

  loading.value = false
  list.value = queryRes.content
  total.value = parseInt(queryRes.totalElements)
}

// ==============================================================
const dialog2 = ref({
  visible: false
})

const dialog3 = ref({
  visible: false,
  title: '增加字典配置'
})
async function handleUpdateItem(id) {
  console.log('handleUpdateItem', id)
  queryParams2.value = {
    dictId: id,
    pageNum: 1,
    pageSize: 20
  }

  let res = await request({
    url: `${BASE_URL}/item/query`,
    method: 'get',
    params: {
      ...queryParams2.value
    }
  })
  dialog2.value = {
    visible: true
  }
  list2.value = res.content
  loading2.value = false
  total2.value = parseInt(res.totalElements)
}

async function handleQueryItem() {
  queryParams2.value.pageNum = 1
  queryParams2.value.pageSize = 20

  let res = await request({
    url: `${BASE_URL}/item/query`,
    method: 'get',
    params: {
      ...queryParams2.value
    }
  })
  dialog2.value = {
    visible: true
  }
  list2.value = res.content
  loading2.value = false
  total2.value = parseInt(res.totalElements)
}
const list2 = ref([])
const total2 = ref(0)
const loading2 = ref(false)

const queryParams2 = ref({
  dictId: 0,
  pageNum: 1,
  pageSize: 20
})

const formItemData = ref({
  orderNum: 100,
  id: null,
  dictId: 0,
  label: '',
  value: '',
  remark: '',
  enabled: true
})
function handleCloseDialogItem() {
  dialog2.value = {
    visible: true
  }
}

async function handleOpenNewItem(id) {
  console.log('handleOpenNewItem', id)

  if (id) {
    let res = await request({
      url: `${BASE_URL}/item/get?id=${id}`,
      method: 'get'
    })
    formItemData.value = res
    dialog3.value = {
      visible: true,
      title: '修改字典配置'
    }
  } else {
    formItemData.value = {
      dictId: queryParams2.value.dictId,
      orderNum: 100,
      id: null,
      label: '',
      value: '',
      remark: '',
      enabled: true
    }
    dialog3.value = {
      visible: true,
      title: '增加字典配置'
    }
  }
}

function handleCloseDialog3() {
  formItemData.value = {
    dictId: queryParams2.value.dictId,
    id: 0,
    label: '',
    value: '',
    enabled: true,
    remark: ''
  }
  dialog3.value = {
    visible: false,
    title: '增加字典配置'
  }
}
const rulesItem = ref({
  label: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  value: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})
async function handleSubmitItem() {
  addFormRef.value.validate(async (isValid) => {
    if (isValid) {
      console.log('handleSubmitItem')
      const id = formItemData.value.id
      if (id) {
        let updateRes = await request({
          url: `${BASE_URL}/item/update`,
          method: 'post',
          data: formItemData.value
        })
        ElMessage.success('修改成功')
      } else {
        let addRes = await request({
          url: `${BASE_URL}/item/save`,
          method: 'post',
          data: formItemData.value
        })
        ElMessage.success('添加成功')
      }
      handleCloseDialogItemNew()
      await handleUpdateItem(formItemData.value.dictId)
    }
  })
}

function handleCloseDialogItemNew() {
  formItemData.value = {
    dictId: queryParams2.value.dictId,
    id: 0,
    label: '',
    value: '',
    enabled: true,
    remark: ''
  }
  dialog3.value = {
    visible: false,
    title: '增加字典配置'
  }
}

async function handleDeleteItem(id) {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      url: `${BASE_URL}/item/delete`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: {
        id: id
      }
    }).then(async () => {
      // await handleQuery()
      await handleUpdateItem(queryParams2.value.dictId)
    })
  })
}

// ==============================================================

onMounted(async () => {
  await handleQuery()
})
</script>
